import target from "./target";

const { ccclass, property } = cc._decorator;

@ccclass
export default class game extends cc.Component {
    //子弹perftb
    @property(cc.Prefab)
    bulletPerfab: cc.Prefab = null;
    @property(cc.Prefab)
    targetPerfab: cc.Prefab = null;
    static inst: game = null;
    //创建子弹资源池
    bulletPool: cc.NodePool = new cc.NodePool();
    targetPool: cc.NodePool = new cc.NodePool();
    canvas: cc.Node = null;
    onLoad() {
        game.inst = this;
        //启用全局碰撞对象
        let manage = cc.director.getCollisionManager();
        manage.enabled = true;
        //此语句是显示碰撞范围。调试观察使用
        // manage.enabledDebugDraw = true;
        this.emenyTarget();
        this.canvas = cc.find('Canvas')
    }

    //添加敌人方块到资源池
    createTarget() {
        let node = this.targetPool.get();
        if (node == null) {
            node = cc.instantiate(this.targetPerfab);
        }
        return node;
    }

    //定时器创建敌人
    emenyTarget() {
        this.schedule(this.onemenyTarget, 1, cc.macro.REPEAT_FOREVER, 0.3)
    }

    ondestroyTarget(node:cc.Node) {
        this.targetPool.put(node);
    }

    onemenyTarget() {//每次最少一个，最多四个
        let index: number = Math.floor(Math.random() * 4);
        for (let i = 0; i < 4; i++) {
            let falg = Math.floor(Math.random() * 2);
            if (falg == 0 && i != index)
                continue;
            let targetNode = this.createTarget();
            if(!targetNode) return;
            targetNode.parent = this.canvas;
            let x = this.canvas.width;
            let y = this.canvas.height;
            let unix = x / 4;
            targetNode.x = unix * i - x / 2 + x / 8;
            targetNode.y = (this.canvas.height + targetNode.y);
            // console.log("还在创建敌人吗")
        }
    }

    gameover() {
        console.log("游戏结束")
    }
    
    start() {
    }

    //添加子弹节点到对象池
    createBullet() {
        let node = this.bulletPool.get();
        if (node == null) {
            node = cc.instantiate(this.bulletPerfab);
        }
        return node;
    }
    //回收子弹节点
    destroyBullet(node: cc.Node) {
        this.bulletPool.put(node);
    }

    // update (dt) {}
}
